package org.testis.serialportmodule.services;

import org.testis.serialportmodule.core.NetworkSerialProvider;
import org.testis.serialportmodule.core.SerialConnectionInterface;
import org.testis.serialportmodule.core.SerialPortProvider;
import org.testis.serialportmodule.data.SerialPortModuleDataObject;
import org.testis.testdriver.AtofEnumaration.AtofSerialPortModuleAction;
import java.util.HashMap;

/**
 *
 * @author nurhat
 */
public class SerialConnectionProvider {

    private static SerialConnectionProvider m_serialConnectionProvider;
    // private SerialConnectionInterface m_serialConnection;
    private HashMap<String, SerialConnectionInterface> list;
    private String m_LastTestPlanId="";

    private SerialConnectionProvider() {
        list = new HashMap<String, SerialConnectionInterface>();
    }

    public static SerialConnectionProvider getInstance() {
        if (m_serialConnectionProvider == null) {
            m_serialConnectionProvider = new SerialConnectionProvider();
        }
        return m_serialConnectionProvider;
    }

    public SerialConnectionInterface getSerialConnectionById(String messageId) {
        return list.get(messageId);
    }

    public void removeSerialConnectionProvider(String messageId) {
        list.remove(messageId);
    }

    public SerialConnectionInterface getSerialConnectionProvider(
            SerialPortModuleDataObject dobj) {
        String useMessageId=dobj.getMessageId();
        if(dobj.getActionType().equals(AtofSerialPortModuleAction.StartConnection.name()))
            m_LastTestPlanId=dobj.getMessageId();
        else if(dobj.getActionType().equals(AtofSerialPortModuleAction.EndConnection.name()))
            m_LastTestPlanId="";
        else if(dobj.getActionType().equals(AtofSerialPortModuleAction.SendCommand.name()))
            useMessageId=m_LastTestPlanId;

        if (getSerialConnectionById(useMessageId) != null) {
            return getSerialConnectionById(useMessageId);
        }else if(!dobj.getActionType().equals(AtofSerialPortModuleAction.StartConnection.name())){
            return null;
        }
        SerialConnectionInterface result;
        if (dobj.isDirectSerial()) {
            result = new SerialPortProvider(dobj.getComPortNo(),
                    dobj.getBaudRate(),
                    dobj.getStopBits(),
                    dobj.getParity(),
                    dobj.getFlowControl(),
                    dobj.getDataBits(),
                    dobj.getMessageId());
        } else {
            result = new NetworkSerialProvider(dobj.getNetworkIp(),
                    dobj.getNetworkPort());

        }
        list.put(dobj.getMessageId(), result);
        return result;
    }
}
